/*  
 * top bar js for header
 * include get user message
 */
'use strict';
(function(){
    require(['jquery-1.10.2.min'],function(){
        require(['lib/top-4.9.min','dist/jquery.cookie.min'],function(){
            // 先把消息通知的轮训放这里
            //hUserPic
            var isWindowActive = true;
            var COOKIE_NAME    = '_msg';
            var STORAGE_NAME   = '_msg_lasttime';
            var $topMsgCnt     = $("#J_topMsgCnt");
            $.cookie( STORAGE_NAME, '');

            // Page Title
            var titleFlash = {
                  timer  : null
                , bValue : true
                , run    : function(){
                    this.bValue = true;
                    clearTimeout(this.timer);

                    var self = this;
                    this.timer = setTimeout(function(){ self.onTimer(); }, 500);
                }
                , onTimer : function () {
                    this.bValue = !this.bValue;
                    document.title = (this.bValue ? '【新消息】' : '【　　　】') + document.title.replace(/(【新消息】)|(【　　　】)/,'');
                    var self = this;
                    this.timer = setTimeout(function(){ self.onTimer(); }, 500 );
                }
                , stop    : function() {
                    if ( this.timer ) {
                        clearTimeout(this.timer);
                        this.timer = null;
                        setTimeout(function(){
                            document.title = document.title.replace(/(【新消息】)|(【　　　】)/,'');
                        } , 0);
                    }
                }
            };
            $(window).blur(function(){
                isWindowActive = false;
            }).focus(function(){
                isWindowActive = true;
                titleFlash.stop();
            });


            // Check Message
            var storageListener   = null;
            var messageTimer      = null;
            var msg_time          = parseInt($topMsgCnt.attr('data-time'));
            var lastStorageResult = null;
            var lastResult        = null;
            var max_error_times   = 3;
            var path              = WJ.parseURL().path;

            function monitorStorage() {
                storageListener = setInterval(function(){
                    var curr = $.cookie(COOKIE_NAME);
                    if(curr != lastStorageResult){
                        lastStorageResult = curr;
                        lastResult = curr;//GJ.jsonDecode(curr);
                        showMessageTip(lastResult , false);
                    }
                } , 1000);

                messageTimer = setTimeout( checkMessage , msg_time );
            }
            function checkMessage() {
                clearTimeout( messageTimer );
                clearInterval( storageListener );

                var lastTime = parseInt( $.cookie(STORAGE_NAME) );

                if(lastTime && (+new Date()) - lastTime <= msg_time) { // get from storage
                    monitorStorage();
                    return;
                }
                $.ajax({
                    url    : '/un/nvc',
                    type   : 'get',
                    success: function(r){
                        r = $.parseJSON(r);
                        if (r.code == 0) {
                            lastResult = r.data.c;
                            showMessageTip(lastResult , false);
                            $.cookie(COOKIE_NAME,lastResult);
                        }

                    },
                    error: function(){
                        max_error_times--;
                    },
                    complete: function(){
                        if ( max_error_times > 0){
                            messageTimer = setTimeout( checkMessage, msg_time );
                            
                            $.cookie(STORAGE_NAME, +(new Date()) );
                        }
                    }
                });
            }
            if ($topMsgCnt[0]) checkMessage();

            var $h5NoticeButton=$('#h5NoticeButton');
            
            function popNotice(){
                if (window.Notification&&Notification.permission == "granted") {
                    var notification = new Notification("赛氪消息提醒：", {
                        body: '您有新的消息，请注意查看~',
                        icon: window.WJ_STA_DOMAIN+'img/logo2020.png',
                        tag: 'notice',
                        renotify: true
                    });
                    notification.onclick = function() {
                        window.location.href=window.WJ_WEB_DOMAIN+'un/l/';
                        notification.close();    
                    };
                }   
            }
            $h5NoticeButton.off('click').on('click',function(){
                if(window.Notification){
                    if (Notification.permission == "granted") {
                        popNotice();
                    } else if (Notification.permission != "denied") {
                        Notification.requestPermission(function (permission) {
                          popNotice();
                        });
                    }
                }
            });

            // check in the message center
            var is_msgCenter = WJ.parseURL().path.match('un/l/')?true:false;

            // Deal with the presentation of the message
            function showMessageTip(r) {
                var $tip;
                if(!r){//如果没有r或者为undifind,给r设为空数组
                    r = [];
                }
                // if in the message center, show the tips of message center and stop show message tip of topbar
                if ( is_msgCenter ) {

                    $.each( r , function( key, val ){
                        val = parseInt(val);
                        $tip = $('#J_msgCenterTip_'+key).find('.tip');
                        $tip.html( val > 0 ? val : '');
                        if (val > 0) {
                            $tip.html(val).show();
                        } else {
                            $tip.hide();
                        }
                    });

                    return false;
                }

                var all_count = 0;
                for ( var i = 0; i < r.length; ++i ) {
                    all_count += r[i];
                    $("#G_tbMsgLnk" + i + " .count").html( r[i] > 0 ? r[i] : "" );
                }
                $.each( r , function( key, val ){
                    all_count += parseInt(val);
                    $tip = $('#J_topTip_'+key).find('.notice-number');
                    $tip.html( val > 0 ? val : '');
                });

                if ( all_count > 0 ) {
                    $topMsgCnt.html( all_count ).show();
                    if( !isWindowActive ) {
                       titleFlash.run();
                    }
                    $h5NoticeButton.click();
                } else {
                    $topMsgCnt.hide();
                    titleFlash.stop();
                }
            }
        });
    });
})();